package chapter02

import scala.collection.mutable

object Test34_FunctionSerior {
  def main(args: Array[String]): Unit = {
    val list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
    //过滤
    for(i<-list){if(i%2==0) println(i)}
    for(i<-list;if(i%2==0)){println(i)}
    val list1 = for (i <- list; if (i % 2 == 0)) yield i
    println(list1)
    println(list.filter(e=>{e%2==0}))
    println(list.filter(_%2==0))
    //映射
    val list2 = for (i <- list) yield i + 1
    val list3 = list.map(e => e + 1)
    println(list2)
    println(list3)
    //扁平化 将高维降低维度
    val nestedList: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
    val list4 = for (i <- nestedList; j <- i) yield j
    println(list4)
    println(nestedList.flatten)
    //映射+扁平化
    val wordList: List[String] = List("hello world", "hello spark", "hello scala")
    println(wordList.map(e=>e.split(" ").toList).flatten)
    println(wordList.flatMap(e => e.split(" ").toList))
    //Reduce简化(归约)通过指定的逻辑将集合中的数据进行聚合，从而减少数据，最终获取结果。
    val list5 = List(1,2,3,5)
    val i = list5.reduce((x, y) => x - y)//1-2-3-4=-8
    val j = list5.sum
    println(i)
    //reduceLeft reduceRight
    println(list5.reduceRight((x,y)=>x-y))//1-(2-(3-5)) 5-3-2-1
    //Fold折叠：化简的一种特殊情况。
    println(list5.fold(10)((x,y)=>x-y))
    //foldLeft foldRight
    println(list5.foldRight(10)((x,y)=>x-y))// 1-(2-(3-(5-10)))
    // 两个Map的数据合并
    val map1 = mutable.Map("a"->1, "b"->2, "c"->3)
    val map2 = mutable.Map("a"->4, "b"->5, "d"->6)
    val map3: mutable.Map[String, Int] = map2.foldLeft(map1) {
      (map, kv) => {
        val k = kv._1
        val v = kv._2
        map(k) = map.getOrElse(k, 0) + v
        map
      }
    }
    println(map3)
  }
}
